package com.yilemall.product.exception;

import com.yilemall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一处理异常
 *
 * @author wangxiaoqi
 * @email wxq_strive@163.com
 * @date 2020-10-18 16:55:45
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.yilemall.product.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        if(result.hasErrors()){
            Map<String,String> map = new HashMap<>();
            //1、获取校验的错误信息
            result.getFieldErrors().forEach((item)->{
                //获取错误提示
                String message = item.getDefaultMessage();
                //获取错误的属性
                String field = item.getField();
                map.put(field,message);
            });
            return R.error(400,"提交的数据不合法").put("data",map);
        }
        return R.error();
    }
}
